package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/14 16:47
 */
public class JZSolution015 {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result  = new ArrayList<>();
        if(p.length()>s.length()) return result;
        int[] pArray = new int[26];
        int[] subStrArray = new int[26];
        for (int i = 0; i < p.length(); i++) {
            char c = p.charAt(i);
            pArray[c - 'a']++;
            char c2 = s.charAt(i);
            subStrArray[c2 - 'a']++;
        }
        if(isAnagrams(pArray,subStrArray)){
            result.add(0);
        }
        for (int i = p.length(); i < s.length(); i++) {
            subStrArray[s.charAt(i-p.length())-'a']--;
            subStrArray[s.charAt(i)-'a']++;
            if(isAnagrams(pArray,subStrArray)){
                result.add(i-p.length()+1);
            }
        }
        return result;
    }

    private boolean isAnagrams(int[] pArray,int[] subStrArray){
        boolean flag = true;
        for (int j = 0; j < pArray.length; j++) {
            if (pArray[j] != subStrArray[j]) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    @Test
    public void test01(){
        String s = "abab", p = "ab";
        List<Integer> result = findAnagrams(s, p);
        System.out.println(result);
    }
}
